<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hyperf_mall
 * @contact  hyperf_mall@163.com
 */

namespace App\Repository;

use App\Model\SmsLogModel;
use Hyperf\Di\Annotation\Inject;

class SmsLogRepository extends BaseRepository
{
    /**
     * @Inject
     * @var SmsLogModel
     */
    protected $model;

    public function sendCode($data)
    {
        if(!$this->checkSend($data['mobile'])){
            return false;
        }else{
            $re = [
                'member_id'     =>$data['member_id'],
                'mobile'        =>$data['mobile'],
                'code'          =>$this->getCode($data['mobile'], $data['retry']??false),
                'content'       =>$data['content']??'',
                'ip'            =>$data['ip'],
            ];

            // TODO 对接第三方短信发送接口

            $this->baseAdd($re);

            return $re['code'];
        }
    }

    /**
     * Notes: 获取验证码
     * Author: Bruce.z
     * DateTime: 2022/6/16 10:30
     * @param $mobile
     * @param bool $is_retry
     * @return string
     */
    private function getCode($mobile, $is_retry = false) :string
    {
        if(!$is_retry) return rand(100000, 999999);

        $row = $this->_searchFactor(['mobile'=>$mobile])->orderByDesc('id')->first(['code']);
        return empty($row) ? rand(100000, 999999) : $row->code;
    }

    /**
     * Notes: 生成短信内容
     * Author: Bruce.z
     * DateTime: 2022/6/16 11:44
     * @return string
     */
    private function getContent():string
    {

    }

    /**
     * Notes:
     * Author: Bruce.z
     * DateTime: 2022/6/15 16:29
     * @param $mobile
     * @return bool
     */
    private function checkSend($mobile) : bool
    {
        // 检测 次/每分钟  次/每小时  次/天
        // 是否针对IP进行检测？
        $today = strtotime(date('Y-m-d'));
        $hour = strtotime(date('Y-m-d H'));
        $min = strtotime(date('Y-m-d H:i'));
        $min_count = $this->_searchFactor(['mobile'=>$mobile,['create_time','>', $min]])->count();
        if($min_count >= 3) return false;

        $hour_count = $this->_searchFactor(['mobile'=>$mobile,['create_time','>', $hour]])->count();
        if($hour_count >= 10) return false;

        $day_count = $this->_searchFactor(['mobile'=>$mobile,['create_time','>', $today]])->count();
        if($day_count >= 50) return false;

        return true;
    }
}
